<script>
import Api from '@/api'
import MAIN_STORE from '@/store/store.js'
import LAYER_UTIL from '@/utils/layer.js';

window.MAIN_STORE = MAIN_STORE;
import { chunk } from 'lodash';
import staticStyleObj from '@/api/styleObj.json';
import ContextMenu from '@/components/ContextMenu/context-menu.vue';
// import geojsonData from '@/api/ts.json';
let heighLightLayer;
let shape;
export default {
  data() {
    return {
      designWidth: 1920,
      designHeight: 1080,
      contextMenuBindData: {
        posX: 0,
        posY: 0,
        show: false
      }
    };
  },
  computed: {
    appInnerStyle() {
      return {
        'width': `${this.designWidth}px`,
        'height': `${this.designHeight}px`,
      }
    },
    showOverView() {
      return ['Search', 'Decision'].indexOf(this.$route.name) !== -1;
    },
    originView() {
      return this.$store.state.originView
    }
  },
  watch: {
  },
  created() {
    window.showFrameRate = function (v) {
      if (!window.scene) { return }
      window.scene.debugShowFramesPerSecond = v;
    }
  },
  components: {
    ContextMenu
  },
  mounted() {
    const that = this;

    function resize() {

      that.designWidth = window.innerWidth;
      that.designHeight = window.innerHeight;

      let clientWidth = documentElement.clientWidth;
      let clientHeight = documentElement.clientHeight;

      let dpr = 1;
      let ratio = 1;

      let widthReal;
      let heightReal;
      if ((clientWidth / clientHeight) > (that.designWidth / that.designHeight)) {
        dpr = clientHeight / that.designHeight;
        widthReal = that.designWidth * clientHeight / that.designHeight;
        heightReal = clientHeight;
        ratio = window.innerWidth / 1920;
      } else {
        dpr = clientWidth / that.designWidth;
        widthReal = clientWidth;
        heightReal = clientWidth * that.designHeight / that.designWidth;
        ratio = window.innerHeight / 1080;
      }
      let appDomOuter = document.getElementById('app-outer');
      appDomOuter.style.width = `${widthReal}px`;
      appDomOuter.style.height = `${heightReal}px`;

      let appDomInner = document.getElementById('app-inner');
      appDomInner.style.transform = `scale(${dpr}) translateX(-50%) translateY(-50%)`;
      documentElement.style.fontSize = 10 * ratio + 'px';
    }
    window.addEventListener('resize', resize)
    setTimeout(() => {
      resize();
      this.init2DViewer();
    }, 0)
  },
  beforeUnmount() {
  },
  methods: {
    showmenu(e) {
      this.contextMenuBindData.posX = e.clientX / 10;
      this.contextMenuBindData.posY = e.clientY / 10;
      this.contextMenuBindData.show = true;
    },
    // 场景初始化 生成全局 scene
    init2DViewer() {
      this.$store.commit('SET_CESIUM_SCENE_CREATED')
      this.init2DMainScene();
    },
    hideBaseImageLayer() {
      const base = viewer.imageryLayers._layers[0];
      if (base) {
        base.alpha = 0;
      }
    },
    loadInOriginView() {
    },
    // 加载主场景
    init2DMainScene() {
      const that = this;
      this.loadInOriginView();
      window.mapIns = MAIN_STORE.GLOBAL_MAP_INS = new ol.Map({
        target: 'map-container',
        layers: new ol.Collection([
          new ol.layer.Group({
            id: 'LAYER_GROUP',
            layers: [
            ]
          })
        ]),
        controls: ol.control.defaults({
          zoom: false
        }),
        view: new ol.View({
          // center: ol.proj.fromLonLat([120.3862161399353, 36.07547667197184]),
          center: ol.proj.fromLonLat(this.originView),
          // center: [13401332.27922657, 4311011.821789091],
          // projection: "EPSG:3857",
          // center: [116.76518883912635, 36.18327910283026],
          // center: [117.03466058455783, 36.69731617537107],
          projection: "EPSG:3857",
          zoom: 12,
          minZoom: 0,
          constrainResolution: true,
          maxZoom: 21,
        }),
      });

      function loadGeoServerReso() {
        var gridsetName = 'EPSG:4326';
        var gridNames = new Array(22).fill(0).map((v, index) => { return `EPSG:4326:${index}` })
        var baseUrl = '/geoserver/pipeline/gwc/service/wmts';
        var styleN = '';
        var format = 'application/vnd.mapbox-vector-tile';
        var infoFormat = 'text/html';
        var layerName = 'pipeline:pipeline-MVT';
        var projection = new ol.proj.Projection({
          code: 'EPSG:4326',
          units: 'degrees',
          axisOrientation: 'neu'
        });
        var resolutions = [0.703125, 0.3515625, 0.17578125, 0.087890625, 0.0439453125, 0.02197265625, 0.010986328125, 0.0054931640625, 0.00274658203125, 0.001373291015625, 6.866455078125E-4, 3.4332275390625E-4, 1.71661376953125E-4, 8.58306884765625E-5, 4.291534423828125E-5, 2.1457672119140625E-5, 1.0728836059570312E-5, 5.364418029785156E-6, 2.682209014892578E-6, 1.341104507446289E-6, 6.705522537231445E-7, 3.3527612686157227E-7];
        var params = {
          'REQUEST': 'GetTile',
          'SERVICE': 'WMTS',
          'VERSION': '1.0.0',
          'LAYER': layerName,
          'STYLE': styleN,
          'TILEMATRIX': gridsetName + ':{z}',
          'TILEMATRIXSET': gridsetName,
          'FORMAT': format,
          'TILECOL': '{x}',
          'TILEROW': '{y}'
        };

        function constructSource() {
          var url = baseUrl + '?'
          for (var param in params) {
            url = url + param + '=' + params[param] + '&';
          }
          url = url.slice(0, -1);

          var source = new ol.source.VectorTile({
            url: url,
            format: new ol.format.MVT({}),
            projection: projection,
            tileGrid: new ol.tilegrid.WMTS({
              tileSize: [256, 256],
              origin: [-180.0, 90.0],
              resolutions: resolutions,
              matrixIds: gridNames
            }),
            wrapX: true
          });
          return source;
        }
        function simpleStyle(feature) {
          const pro = feature.getProperties();
          pro.corlor = pro.corlor || pro['颜色']
          if(!pro.corlor) {
            console.log(pro, 'pro')
          }
          const color = pro.corlor? `rgb(${pro.corlor})`: '#ffe500'
          return new ol.style.Style({
            // fill: new ol.style.Fill({
            //   color: '#ADD8E6'
            // }),
            stroke: new ol.style.Stroke({
              color: color,
              width: 2
            })
          })
        }

        var layer = new ol.layer.VectorTile({
          source: constructSource(),
          style: simpleStyle
        });
        layer.setZIndex(10);
        MAIN_STORE.GLOBAL_MAP_INS.addLayer(layer);
      }

      // setTimeout(() => {
      //   loadGeoServerReso();
      // }, 1000)

      return
      // const styleObj = 'http://localhost:8090/iserver/services/map-mvt-pipeline-1128-mvt/restjsr/v1/vectortile/maps/pipeline-1128-mvt/style.json'
      // const styleObj = 'http://localhost:8090/iserver/services/map-mvt-pipeline-1231-mvt/restjsr/v1/vectortile/maps/pipeline-1231-mvt/style.json'
      const styleObj = staticStyleObj;
      // const styleObj = 'http://localhost:8090/iserver/services/map-ceshiguanxian/restjsr/v1/vectortile/maps/pipetest/style.json';
      MAIN_STORE.STYLE_OBJ = styleObj;
      const style = new ol.supermap.MapboxStyles({
        style: styleObj,
        selectedStyle: function (feature) {
          const geometry = feature.get('geometry');
          const isPoint = geometry.flatCoordinates.length <= 2;
          if (isPoint) {
            return new ol.style.Style({
              geometry: new ol.geom.Point(geometry.flatCoordinates),
              image: new ol.style.Circle({
                radius: 10,
                fill: new ol.style.Fill({
                  color: 'rgba(0,200,0,0.9)',
                  width: 5
                })
              }),
            })
          } else {
            return new ol.style.Style({
              stroke: new ol.style.Stroke({
                color: 'rgba(0,200,0,0.9)',
                width: 10
              }),
            })
          }
        }
      });
      MAIN_STORE.MAPBOX_STYLE = style;
      const source = new ol.source.VectorTileSuperMapRest({
        style: styleObj,
        projection: 'EPSG:4326',
        format: new ol.format.MVT({
          featureClass: ol.Feature
        })
      });
      let vectorLayer;
      style.on('styleloaded', function () {
        vectorLayer = new ol.layer.VectorTile({
          declutter: true,
          source: source,
          style: style.getStyleFunction()
        });
        vectorLayer.setZIndex(10);
        MAIN_STORE.VECTOR_LAYER = vectorLayer;
        MAIN_STORE.GLOBAL_MAP_INS.addLayer(vectorLayer);
      });
    }
  },
};
</script>

<template>
  <div id="app-outer">
    <!-- @contextmenu.prevent="showmenu($event)" -->
    <div id="map-container" @click="() => {
      contextMenuBindData.show = false;
    }" :class="{
      'show-overview': showOverView
    }"></div>
    <div id="app-inner" :style="appInnerStyle" class="cesium-container-loading" v-loading="globalLoading"
      element-loading-background="rgba(0, 0, 0, 0.5)">
      <!-- 路由 -->
      <div class="router-view has-points-events">
        <RouterView />
      </div>
      <!-- 遮罩 -->
      <div class="mask-custom"></div>
    </div>
    <!-- 右击面板 -->
    <context-menu v-bind="contextMenuBindData"></context-menu>
  </div>


</template>
<style>
.ol-overviewmap {
  opacity: 0;
  pointer-events: none;
}

.show-overview .ol-overviewmap {
  opacity: 1;
  pointer-events: all;
}
</style>

<style lang="less" scoped>
#map-container {
  width: 100%;
  height: 100%;
}

#app-inner {
  transform-origin: 0px 0px;
  position: absolute;
  left: 50%;
  top: 50%;
  pointer-events: none;
}
</style>
